package leetcode;

import java.util.HashMap;
import java.util.HashSet;

public class Leetcode547NumberOfProvince {

    public int find(int[] s, int x) {
        while (s[x] != x)
            x = s[x];
        return x;
    }

    public void union(int[] s, int x, int y) {
        int xRoot = find(s,x);
        int yRoot = find(s,y);
        if (xRoot == yRoot) return;
        s[xRoot] = yRoot;
    }

    public int findCircleNum(int[][] isConnected) {
        int[] s = new int[isConnected.length];
        for (int i = 0; i < isConnected.length; i++) {
            s[i] = i;
        }
        
        for (int i = 0; i < isConnected.length; i++) {
            for (int j = i + 1; j < isConnected.length; j++) {
                if (i == j) continue;
                if (isConnected[i][j] == 1) {
                    union(s,i,j);
                }
            }
        }
        HashSet<Integer> hashSet = new HashSet<>();
        for (int i = 0; i < isConnected.length; i++) {
            System.out.println(s[i]);
            hashSet.add(find(s,i));
        }
        return hashSet.size();
    }

    public static void main(String[] args) {
        int[][] i = {{1,0,0,1},{0,1,1,0},{0,1,1,1},{1,0,1,1}};
        Leetcode547NumberOfProvince l = new Leetcode547NumberOfProvince();
        l.findCircleNum(i);
    }
}
